package com.bat.conf;

import com.bat.util.R;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;

/**
 * 统一异常处理器
 *
 * @author zpf
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionConf {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleNullPointorException(NullPointerException e) {
        logger.error(e.getMessage(), e);
        String msg = e.getMessage();
        return R.fail(msg);
    }
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.fail(e.getMessage());
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return R.fail(400, e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error(e.getMessage(), e);
        return R.fail(400, e.getMessage());
    }


    @ExceptionHandler(ConstraintViolationException.class)
    public R handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);
        return R.fail(500, e.getMessage());
    }


    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error(e.getMessage(), e);
        return R.fail(400, "参数映射错误，请检查参数");
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public R handleMediaTypeException(HttpMediaTypeNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return R.fail(107, "MediaType错误，请用\"application/json\"方式提交");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(NoHandlerFoundException e) {
        logger.error(e.getMessage(), e);
        return R.fail(404, "路径不存在，请检查路径是否正确");
    }

}
